package com.qolome.product.service.impl;

import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.qolome.enums.ProductStatusEnum;
import com.qolome.enums.ResultEnum;
import com.qolome.product.dto.request.CartDTO;
import com.qolome.product.dto.response.ProductInfoResponseDto;
import com.qolome.product.exceotion.ProductException;
import com.qolome.product.model.ProductInfo;
import com.qolome.product.repository.ProductInfoRepository;
import com.qolome.product.service.ProductService;

/**
 * @author Qolome
 * @version V1.0
 * @Description 商品
 * @date 2020年 01月20日 09:46:13
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoRepository productInfoRepository;
    
    @Autowired
    AmqpTemplate amqpTemplate;

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }
    
    @Override
    public List<ProductInfo> findList(List<String> productIdList) {
        return productInfoRepository.findByProductIdIn(productIdList);
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> decreaseStockInputList) {
        for (CartDTO decreaseStockInput: decreaseStockInputList) {
            Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(decreaseStockInput.getProductId());
            //判断商品是否存在
            if (!productInfoOptional.isPresent()){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            ProductInfo productInfo = productInfoOptional.get();
            //库存是否足够
            Integer result = productInfo.getProductStock() - decreaseStockInput.getProductQuantity();
            if (result < 0) {
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
            ProductInfoResponseDto productInfoResponseDto = new ProductInfoResponseDto();
            BeanUtils.copyProperties(productInfo, productInfoResponseDto);
            amqpTemplate.convertAndSend("order",new Gson().toJson(productInfoResponseDto));
        }
    }
}
